<?php 
/**
 * Register or login of users
 */
if(isset($_POST['tag']) && !empty($_POST['tag'])){
	$tag = $_POST['tag'];
	
	require_once __DIR__ . '/db_functions.php';
	$db = new DB_Functions();
	
	$response = array("tag" => $tag, "success" => 0, "error" => 0);
	if($tag == 'login'){
		$email = $_POST['email'];
		$password = $_POST['password'];
		
		// check for user
		$user = $db->getUserByEmailAndPassword($email, $password);
		if($user != false){
			// user found
			// echo json with success = 1
			$response["success"] = 1;
			$response["uid"] = $user["unique_id"];
			$response["user"]["name"] = $user["name"];
			$response["user"]["email"] = $user["email"];
			
			echo utf8_encode(json_encode($response));
		} else {
			// user not found
			// echo json with error = 1
			$response["error"] = 1;
			$response["error_msg"] = "Incorrect email or password!";
			
			echo utf8_encode(json_encode($response));
		}
	} else if($tag == 'register'){
		// Request type is Register new user
		$name = $_POST['name'];
		$email = $_POST['email'];
		$password = $_POST['password'];
		$gcm_regid = $_POST["regId"]; // GCM Registration ID
		
		//$gcm = new GCM();
		
		// check if user id already existed
		if($db->isUserExisted($email)){
			// user is already existed - error response
			$response["error"] = 2;
			$response["error_msg"] = "User already existed";
			echo utf8_encode(json_encode($response));
		} else {
			// store user
			$user = $db->storeUser($name, $email, $password, $gcm_regid);
			$registatoin_ids = array($gcm_regid);
			
			/* $message = array("users" => "user");
			$result = $gcm->send_notification($registatoin_ids, $message);
			echo $result; */
			if($user){
				// user stored successfully
				$response["success"] = 1;
				$response["uid"] = $user["unique_id"];
				$response["user"]["name"] = $user["name"];
				$response["user"]["email"] = $user["email"];
				
				echo utf8_encode(json_encode($response));
			} else {
				// user failed to store
				$response["error"] = 1;
				$response["error_msg"] = "Error occured in Registartion";
				echo utf8_encode(json_encode($response));
			}
		}
	}
	else {
		echo "Invalid Request";
	}
} else {
    echo "Access Denied";
}
?>